package com.tuxing.draa_data.util;

import com.tuxing.draa_data.pojo.ChaoXingDiff;
import com.tuxing.draa_data.pojo.ChaoXingPeri;
import com.tuxing.draa_data.pojo.center.NewDcBibliographyPeri;
import com.tuxing.draa_data.pojo.center.NewDcBibliographyPeriDetail;
import com.tuxing.draa_data.service.ChaoXingPeriService;
import com.tuxing.draa_data.service.NewDcBibliographyPeriService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Component
@Slf4j
public class ChaoXingPeriUtil {

   @Autowired
   private ChaoXingPeriService chaoXingPeriService;

   @Autowired
   private NewDcBibliographyPeriService newDcBibliographyPeriService;


   private static final int NUMBER = 1000;//一次读取数据量
   private static final int TITLE_P_ISSN_MATCH = 1;//题名标准号匹配
   private static final int P_ISSN_MATCH = 2;//P_ISSN匹配
   private static final int O_ISSN_MATCH = 3;//O_ISSN匹配
   private static final int TITLE_MATCH = 4;//TITLE匹配 只有TITLE匹配上且 P_ISSN和O_ISSN为空
   private static final int TITLE_ONLY_MATCH = 5;//TITLE匹配 只有TITLE匹配上且 P_ISSN或O_ISSN不为空
   private static final int CHAOXING_DATA = 0;//超星数据
   private static final String SUFFIX = "c467d85f-4048-423b-9946-5a2bf4d4ece9";//超星数据
   private static final String CHINESE = "中文";
   private static final String ENGLISH = "外文";
   private static final String DCTERMS = "DCTERMS";

//   @PostConstruct
   @Transactional
   public void initData(){
       log.info("数据更新任务开始！");
       //获取所有超星数据
       List<ChaoXingPeri> cxpList = chaoXingPeriService.findAllData();
       List<ChaoXingPeri> updateCxpList = new ArrayList<>();//更新过的ChaoXingPeri数据
       if(null == cxpList || cxpList.size() == 0){
           log.info("超星数据为空任务结束！");
           return;
       }
       Integer count = newDcBibliographyPeriService.findCount();
       if(null == count || count==0){
           log.info("本地数据为空任务结束！");
           return;
       }

       Map<String, ChaoXingPeri> map = new HashMap<>();
       for(ChaoXingPeri cxp : cxpList){
            if(StringUtils.isNotBlank(cxp.getIssn())&&StringUtils.isNotBlank(cxp.getMagName())){
                map.put((cxp.getMagName()+" "+cxp.getIssn()).toLowerCase(),cxp);//题名和issn号都存在 拼在一起当键
                map.put(cxp.getIssn().toLowerCase(),cxp);
                map.put(cxp.getMagName().toLowerCase(),cxp);
            }else if(StringUtils.isNotBlank(cxp.getIssn())){
                map.put((SUFFIX+cxp.getIssn()).toLowerCase(),cxp);
            }else if(StringUtils.isNotBlank(cxp.getMagName())){
                map.put((SUFFIX+cxp.getMagName()).toLowerCase(),cxp);
            }
       }
       if(map.size()==0){
           return;
       }
       List<NewDcBibliographyPeri> ndbpList;
       List<NewDcBibliographyPeri> ndbpToUpdateList = new ArrayList<>();
       String issn;
       String oissn;
       String title;
       String titleAndIssn;
       int endPage = count % NUMBER == 0 ? count / NUMBER : count / NUMBER + 1;
       for (int i = 0; i < endPage; i++) {
           try {
               int start = i * NUMBER;
               ndbpList = newDcBibliographyPeriService.findLimit(start, NUMBER);
               ndbpToUpdateList.clear();
               log.info("{}条数据，开始更新数据库！", ndbpList.size());
               for(NewDcBibliographyPeri ndbp : ndbpList){
                   titleAndIssn = null;
                   issn = null;
                   title = null;
                   oissn = null;
                   if(StringUtils.isBlank(ndbp.getMagId())){
                       if(StringUtils.isNotBlank(ndbp.getPIssn())){
                           issn= ndbp.getPIssn().toLowerCase();
                       }
                       if(StringUtils.isNotBlank(ndbp.getOIssn())){
                           oissn= ndbp.getOIssn().toLowerCase();
                       }
                       if(StringUtils.isNotBlank(ndbp.getTitle())){
                           title= ndbp.getTitle().toLowerCase();
                       }
                       if(StringUtils.isNotBlank(issn)&&StringUtils.isNotBlank(title)){
                           titleAndIssn = (title+" "+issn).toLowerCase();
                       }

                       if(StringUtils.isNotBlank(titleAndIssn) && map.containsKey(titleAndIssn)){
                           ndbp.setMagId(map.get(titleAndIssn).getMagId());
                           ndbp.setDataType(TITLE_P_ISSN_MATCH);
                           ndbpToUpdateList.add(ndbp);
                           updateCxpList.add(map.get(titleAndIssn));
                       }else if(StringUtils.isNotBlank(issn) && (map.containsKey(issn)|| map.containsKey(SUFFIX+issn))){
                           if(map.containsKey(SUFFIX+issn)){
                               issn = SUFFIX+issn;
                           }
                           ndbp.setMagId(map.get(issn).getMagId());
                           ndbp.setDataType(P_ISSN_MATCH);
                           ndbpToUpdateList.add(ndbp);
                           updateCxpList.add(map.get(issn));
                       }else if(StringUtils.isNotBlank(oissn) && (map.containsKey(oissn)|| map.containsKey(SUFFIX+oissn))){
                           if(map.containsKey(SUFFIX+oissn)){
                               oissn = SUFFIX+oissn;
                           }
                           ndbp.setMagId(map.get(oissn).getMagId());
                           ndbp.setDataType(O_ISSN_MATCH);
                           ndbpToUpdateList.add(ndbp);
                           updateCxpList.add(map.get(oissn));
                       }else if(StringUtils.isNotBlank(title) && (map.containsKey(title) || map.containsKey(SUFFIX+title))){
                           if(map.containsKey(SUFFIX+title)){
                               title = SUFFIX+title;
                           }
                           if(StringUtils.isBlank(issn) && StringUtils.isBlank(oissn)){
                               if(StringUtils.isBlank(ndbp.getPIssn())&&StringUtils.isNotBlank(map.get(title).getIssn())){
                                   ndbp.setPIssn(map.get(title).getIssn());
                               }
                               ndbp.setMagId(map.get(title).getMagId());
                               ndbp.setDataType(TITLE_MATCH);
                           }else {
                               ndbp.setMagId(map.get(title).getMagId());
                               ndbp.setDataType(TITLE_ONLY_MATCH);
                           }
                           ndbpToUpdateList.add(ndbp);
                           updateCxpList.add(map.get(title));
                       }
                   }
               }
               log.info("{}条数据，需要更新！", ndbpToUpdateList.size());
               if(ndbpToUpdateList.size()>0){
                   newDcBibliographyPeriService.saveOrUpdateBatch(ndbpToUpdateList);
               }
           }catch (Exception e){
               log.error("数据更新失败，失败原因：" + e.getMessage(), e);
               throw new RuntimeException();
           }
           log.info("数据更新成功！");
       }
        //获取cxpList和updateCxpList的差集  cxpList  updateCxpList
       List<ChaoXingDiff> cxDiffList = getDiff(cxpList, updateCxpList);
       newDcBibliographyPeriService.saveAllData(cxDiffList);
       log.info("数据更新任务结束！");
   }

   public List<ChaoXingDiff> getDiff(List<ChaoXingPeri> cxpList, List<ChaoXingPeri> updateCxpList){
       List<ChaoXingDiff> cxDiffList = new ArrayList<>();
       Set<String> diffSet = new HashSet<>();
       for (ChaoXingPeri updateCxp : updateCxpList){
           diffSet.add(updateCxp.getMagId());
       }

       for(ChaoXingPeri cxp : cxpList){
           if(!diffSet.contains(cxp.getMagId())){
               ChaoXingDiff chaoXingDiff = new ChaoXingDiff();
               NewDcBibliographyPeri ndbp = new NewDcBibliographyPeri();
               ndbp.setMagId(cxp.getMagId());
               ndbp.setDataType(CHAOXING_DATA);
               ndbp.setPIssn(cxp.getIssn());
               ndbp.setTitle(cxp.getMagName());
               if(null != cxp.getChoren() && cxp.getChoren() == 1){
                   ndbp.setLangCode(1);
               }else {
                   ndbp.setLangCode(2);
               }
               ndbp.setMdType(DCTERMS);
               ndbp.setPublisher(cxp.getUnit());
               chaoXingDiff.setNdbp(ndbp);
               NewDcBibliographyPeriDetail ndbpd = new NewDcBibliographyPeriDetail();
               ndbpd.setImpactFactor(cxp.getInfluenceFactor());
               ndbpd.setSubject(cxp.getSubjectName());
               ndbpd.setCitationIndex(cxp.getRecodeRange());
               chaoXingDiff.setNdbpd(ndbpd);
               cxDiffList.add(chaoXingDiff);
            }
        }
       return cxDiffList;
   }

}
